import React, {useEffect, useRef, useState} from 'react';
import { Card, Col, Row, Avatar, List, Tag, Drawer } from 'antd'
import { EditOutlined, EllipsisOutlined, SettingOutlined } from '@ant-design/icons'
import axios from "axios";
import {Link} from "react-router-dom";
import * as Echarts from 'echarts'
import _ from 'lodash'

const {Meta}=Card

const Home = () => {
    const [viewList,setViewList]=useState([])
    const [starList,setStarList]=useState([])
    const [allList,setAllList]=useState([])
    const {username,region,role:{roleName}} =JSON.parse(localStorage.getItem('token'))
    const barRef = useRef()
    const pieRef = useRef()
    const [visible, setVisible] = useState(false);
    const [pieChart, setPieChart] = useState(null);

    const onClose = () => {
        setVisible(false);
    };

    useEffect(()=>{
        axios.get('news?publishState=2&_expand=category&_sort=view&_order=desc&_limit=6').then(
            res=>{
                setViewList(res.data)
            }
        )
    },[])
    useEffect(()=>{
        axios.get('news?publishState=2&_expand=category&_sort=star&_order=desc&_limit=6').then(
            res=>{
                setStarList(res.data)
            }
        )
    },[])

    useEffect(()=>{
        axios.get('news?publishState=2&_expand=category').then(
            res=>{
                renderBarView(_.groupBy(res.data,item=>item.category.title))
                setAllList(res.data)
            }
        )
        return ()=>{
            window.onresize=null
        }
    },[])



    const renderBarView =(obj)=>{
        // 基于准备好的dom，初始化echarts实例
        const myChart = Echarts.init(barRef.current);

        // 指定图表的配置项和数据
        const option = {
            title: {
                text: '新闻分类'
            },
            tooltip: {},
            legend: {
                data: ['数量']
            },
            xAxis: {
                data: Object.keys(obj),
                axisLabel:{
                    interval:0,
                    rotate:"45"
                }
            },
            yAxis: {
                minInterval:1
            },
            series: [
                {
                    name: '数量',
                    type: 'bar',
                    data: Object.values(obj).map(item=>item.length)
                }
            ]
        };

        // 使用刚指定的配置项和数据显示图表。
        myChart.setOption(option);
        window.onresize=()=>{
            myChart.resize()
        }
    }

    const renderPieView =()=>{
        const currentList = allList.filter(item=>item.author===username)
        const groupObj = _.groupBy(currentList,item=>item.category.title)
        const list = []
        for(let i in groupObj){
            list.push({
                name:i,
                value:groupObj[i].length
            })
        }

        // 基于准备好的dom，初始化echarts实例
        let myChart
        if(!pieChart){
            myChart = Echarts.init(pieRef.current)
            setPieChart(myChart)
        }else {
            myChart = pieChart
        }

        // 指定图表的配置项和数据
        const option = {
            title: {
                text: '个人新闻总览',
                left: 'center'
            },
            tooltip: {
                trigger: 'item'
            },
            legend: {
                orient: 'vertical',
                left: 'left'
            },
            series: [
                {
                    name: 'Access From',
                    type: 'pie',
                    radius: '50%',
                    data: list,
                    emphasis: {
                        itemStyle: {
                            shadowBlur: 10,
                            shadowOffsetX: 0,
                            shadowColor: 'rgba(0, 0, 0, 0.5)'
                        }
                    }
                }
            ]
        }

        // 使用刚指定的配置项和数据显示图表。
        option&&myChart.setOption(option);
    }


    return (
        <div className="site-card-wrapper">
            <Row gutter={16}>
                <Col span={8}>
                    <Card title="用户最常浏览" bordered={true}>
                        <List
                            size='large'
                            dataSource={viewList}
                            renderItem={item => (
                                <List.Item>
                                    <Link to={`/news-manage/preview/${item.id}`}>{item.title}</Link>
                                </List.Item>
                            )}
                        />
                    </Card>
                </Col>
                <Col span={8}>
                    <Card title="用户点赞最多" bordered={true}>
                        <List
                            size='large'
                            dataSource={starList}
                            renderItem={item => (
                                <List.Item>
                                    <Link to={`/news-manage/preview/${item.id}`}>{item.title}</Link>
                                </List.Item>
                            )}
                        />
                    </Card>
                </Col>
                <Col span={8}>
                    <Card
                        cover={
                            <img
                                alt="example"
                                src="https://gw.alipayobjects.com/zos/rmsportal/JiqGstEfoWAOHiTxclqi.png"
                            />
                        }
                        actions={[
                            <SettingOutlined key="setting" />,
                            <EditOutlined key="edit" />,
                            <EllipsisOutlined key="ellipsis" onClick={()=>{
                                setTimeout(()=>{
                                    setVisible(true)
                                    renderPieView()
                                },0)
                            }}/>,
                        ]}
                    >
                        <Meta
                            avatar={<Avatar src="https://joeschmoe.io/api/v1/random" />}
                            title={username}
                            description={
                                <div>
                                    <b>{region?region:'全球'}</b>
                                    <Tag color={"blue"} style={{margin:"5px 15px"}}>{roleName}</Tag>
                                </div>
                            }
                        />
                    </Card>
                </Col>
            </Row>

            <Drawer size={"large"} title="个人详情" placement="right" onClose={onClose} visible={visible}>
                <div ref={pieRef} style={{width: "100%",height:"400px",margin:"40px 0"}}></div>
            </Drawer>

            <div ref={barRef} style={{width: "100%",height:"400px",margin:"40px 0"}}>

            </div>
        </div>
    );
};

export default Home;